package com.xiangyun.resource.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.xiangyun.utils.MapperUtils;
import com.xiangyun.utils.RSAUtils;

@Component
public class ResourceTokenAuthFilter extends OncePerRequestFilter{

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		//解析请求头的token
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		List authList = new ArrayList();
		String token = request.getHeader("jsonToken");
		if(null != token) {
			//对json解密
			String json = RSAUtils.decryptPassWord(token);
			try {
				//获取json
				jsonMap = MapperUtils.json2map(json);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String userName = (String) jsonMap.get("userName");
			try {
				authList = MapperUtils.json2list((String)jsonMap.get("authList"),String[].class);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//将用户与身份信息存放到用户token当中
			UsernamePasswordAuthenticationToken authenticationToken = 
					new UsernamePasswordAuthenticationToken(userName, null , authList);
			authenticationToken.setDetails(new WebAuthenticationDetails(request));
			
			SecurityContextHolder.getContext().setAuthentication(authenticationToken);
		}
		
		filterChain.doFilter(request, response);
	}

}
